package kmp;

import java.util.Deque;
import java.util.LinkedList;

public class leetCode402_removeKdigits {
    public static void main(String[] args) {

        leetCode402_removeKdigits a = new leetCode402_removeKdigits();
        String s = a.removeKdigits("1432219", 3);
        System.out.println(s);

    }

    public String removeKdigits(String num, int k) {
        Deque<Character> deque = new LinkedList<>();
        int length = num.length();
        for (int i = 0; i < length; i++) {
            char digit = num.charAt(i);
            while (!deque.isEmpty() && k > 0 && deque.peekLast() > digit){
                deque.pollLast();
                k--;
            }
            deque.addLast(digit);
        }
        for (int i = 0; i < k; i++) {
            deque.pollLast();
        }

        StringBuilder stringBuilder = new StringBuilder();
        boolean first = true;
        while (!deque.isEmpty()){
            char digit = deque.pollFirst();
            if(first && digit == '0'){
                continue;
            }
            first = false;
            stringBuilder.append(digit);
        }
        return stringBuilder.length() == 0 ? "0" : stringBuilder.toString();



    }
}
